#!/usr/bin/perl

# load modules
require "./electric_bulletin_board-lib.pl";
require "./config.pl";


# show header
&ui_print_header(undef, $text{'index_title'}, "", undef, 1, 1);

# create temp directory
$temporary_path = &transname();
mkdir ("$temporary_path");

# read argument in %getin
&ReadParse(\%getin, "GET");

# get upload data
my $upid = $getin{'id'};
&ReadParseMime(undef, \&read_parse_mime_callback, [$upid]);
if ($in{'upload_filename'} eq "") {
	&error("None Upload FileName");
}
my @ExtensionArray = qw(bmp jpg png);  # File Extension
my $filecheck = 0;
foreach my $extension (@ExtensionArray) {
	if ($in{'upload_filename'} =~ /\.$extension$/i) {
		$filecheck = 1;
		last;
	}
}
unless ($filecheck) {
	&error("Upload File Is NOT Image");
}

# create upid directory
my $upload_path = "$temporary_path/$upid";
mkdir ($upload_path);

# create pattern directory
$pattern_path = "$module_root_directory/pattern";
unless (-e "$pattern_path") {
	mkdir ("$pattern_path") || &error("フォルダが作成できません");
}

# save file
open (FH, ">$upload_path/$in{'upload_filename'}") || &error("ファイルを保存できません。");
binmode (FH);
print FH $in{'upload'};
close (FH);

# change file list
my $imagefilename = "$upid.pgm";
my %filelist = ();
&read_file("$module_root_directory/pattern/file.list", \%filelist);
$filelist{"$imagefilename"} = $in{'upload_filename'};
&write_file("$module_root_directory/pattern/file.list", \%filelist);

# convert image format
&convert_image("$upload_path/$in{'upload_filename'}", "$pattern_path/$imagefilename");

# show massage
print "<h3>Successfully uploaded the following files :</h3>";
print "<h3>File Name :$in{'upload_filename'}</h3>";
#/tmp/miku014.jpg (472739 bytes)

# show footer
&ui_print_footer("index.cgi", "パターン作成");

